<?php
/**
 * 考勤管理控制器
 * @author ZhouYP
 **/
namespace Admin\Controller;
use Common\Controller\WahahabaseController;
class TeamWorksController extends WahahabaseController{
	protected $twork_model,$type_model,$att_model;

	public function _initialize() {
		parent::_initialize();
		$this->twork_model = D("Common/Teamwork");
		$this->type_model = D("Common/TeamworkType");
		$this->comm_model = D("Common/TeamworkComm");
		$this->study_model = D("Common/TeamworkStudy");
		$this->att_model = D("Common/Attachment");
		$this->users_model = D("Common/Users");
		$this->departs_model = D("Common/Department");
		$this->userlog_model = D("Common/TeamworkUserlog");
	}
	/**
     *  主页
     */
	public function index(){
		//当前登录人
		$admin_id = session('ADMIN_ID');
		//$user_name = $this->users_model->where(array('id'=>$admin_id))->find();
		$where = " 1=1 ";
		
		/*查询与我有关的任务 参与 负责 派发或审批 start*/
		if($_GET['user_id']){
			$_SESSION['user_id_twork'] = $_GET['user_id'];
		}
		$user_id = $_SESSION['user_id_twork'] ? $_SESSION['user_id_twork'] : 'all';
		if($user_id == 1){//我负责的
			$where .= " and t.resp_id = ".$admin_id;
		}else if($user_id == 2){//我派发的
			$where .= " and t.propose_id = ".$admin_id;
		}else if($user_id == 3){//我参与的
			$where .= " and find_in_set('".$admin_id."',t.part_ids)";
		}else if($user_id == 4){//我审批的
			$where .= " and t.approve_id = ".$admin_id;
		}else{
			$where .= " and ( t.resp_id = ".$admin_id." or t.propose_id = ".$admin_id." or find_in_set('".$admin_id."',t.part_ids) or t.approve_id = ".$admin_id.")";
		}
		/*查询与我有关的任务 参与 负责 派发或审批 end */
		
		/* 插任务状态  start */
		/*if($_GET['status']){
			$_SESSION['status_twork'] = $_GET['status'];
		}
		$status = $_SESSION['status_twork'] ? $_SESSION['status_twork'] : '2';*/
		$status = $_GET['status'] ? $_GET['status'] : '2';
		if($status && $status != 'all'){
			$where .= " and t.status = ".$status;
		}
		/* 插任务状态  start */
		
		/* 类型筛选  start  */
		if($_GET['type_id']){
			$_SESSION['type_id_twork'] = $_GET['type_id'];
		}
		$type_id = $_SESSION['type_id_twork'] ? $_SESSION['type_id_twork'] : 'all';
		if($type_id && $type_id != 'all'){
			$where .= " and t.type_id = ".$type_id;
		}
		/* 类型筛选  end  */
		/* 时间筛选  start*/
		/*if($_GET['week']){
			$_SESSION['week_twork'] = $_GET['week'];
		}
		$week = $_SESSION['week_twork'] ;*/
		$week = $_GET['week'] ;
		if($week){
			$now = date("w");
			$time_str = ($week-$now)*24*3600 ;//当前时间差
			$start_time = strtotime(date("Y-m-d")) + $time_str;//开始时间
			$end_time = strtotime(date("Y-m-d")) + $time_str + (24*3600);//结束时间
			
			$where .= " and ((t.start_time >= ".$start_time." and t.start_time <= ".$end_time.") or (t.start_time >= ".$start_time." and t.end_time <= ".$end_time.") or (t.start_time <= ".$start_time." and t.end_time >= ".$end_time.") or (t.end_time >= ".$start_time." and t.end_time <= ".$end_time.") )";
		}
		/* 时间筛选  end*/
		$count=$this->twork_model->alias("t")->where($where)->count();
		$page = $this->page($count, 20);
        $results = $this->twork_model->alias("t")
            ->field('t.*,ty.name tname,ty.type_id tyid,c.comm_num,u.study_num,us.real_name')
            ->join(array(
            	 ' LEFT JOIN '.C('DB_PREFIX').'teamwork_type ty ON ty.id = t.type_id',//类型
				 ' LEFT JOIN (select id,twork_id,count(id) comm_num from hzzy_teamwork_comm group by twork_id) c ON c.twork_id = t.id',//沟通
				 ' LEFT JOIN (select id,twork_id,count(id) study_num from hzzy_teamwork_study group by twork_id) u ON u.twork_id = t.id',//心得
				 ' LEFT JOIN '.C('DB_PREFIX').'users us ON us.id = t.resp_id'
            	))
            ->where($where)
            ->order("t.pub_time desc")
            ->limit($page->firstRow, $page->listRows)
            ->select();
		$this->assign("results", $results);//传递总数据
		$types = $this->type_model->where('type_id = 1')->order("id ASC")->select();
        $this->assign("types",$types);//传递分类数据
		$this->assign("user_id",$user_id);
		$this->assign("type_id",$type_id);
		$this->assign("status",$status);
		//$this->assign("user_name",$user_name);
		$this->assign("week",$week);
        $this->display();
	}

	/**
     *  添加
     */
	public function add(){
		$types = $this->type_model->order("id ASC")->select();
        $this->assign("types",$types);
		$users = $this->users_model->order("id ASC")->select();
        $this->assign("users",$users);
		$departs = $this->departs_model->select();
		foreach($departs as $key=>$val){
			$us = $this->users_model->where("department_id = ".$val['id'])->order("id ASC")->select();
			$departs[$key]['users'] = $us;
		}
		$this->assign("departs",$departs);
		$this->display();
	}
	public function add_post2(){
		if(IS_POST){
			if(empty($_POST['file_name'])){
				$this->error("图纸名称不能为空！");
			}
			if(empty($_POST['upFile'])){
				$this->error("请选择要上传的图纸文件！");
			}var_dump($_POST);exit;
			if ($this->file_model->create()!==false) {
				$data = $_POST;
				$data['file_model'] = '1';
				$data['manager_id'] = session('ADMIN_ID');
				$data['upload_time'] = time();
				if($_POST['upExcel']){
					$this->import();
				}
				
				for($i = 0; $i < count($_POST['fileName']); $i++){
					$files = array(
						//'file_name'	=> $_POST['fileName'][$i],
						'file_path'	=> $_POST['filePath'][$i],
						'file_type'	=> $_POST['postfix'][$i],
						'file_size'	=> $_POST['file_size'][$i]/1000,
					);
					$data = array_merge($data, $files);
					$result = $this->file_model->add($data);
				}
				if ($result!==false) {
					$this->success("添加成功！", U("DrawingUpload/index"));
				} else {
					$this->error("添加失败！");
				}
			} else {
				$this->error($this->file_model->getError());
			}
		}
	}
	/*
	添加
	*/
	public function add_post(){
		if(IS_POST){
			//var_dump($_POST);exit;
			if($_POST['title'] == ''){
				$this->error("请填写工作任务名称！");
			}
			if ($this->att_model->create()!==false && $this->twork_model->create()!==false) {
				$data = $_POST;
				
				$data['propose_id'] = session('ADMIN_ID');
				$data['upload_time'] = time();
				$data['pub_time'] = time();
				$data['status'] = 1;//未开始
				$data['start_time'] = strtotime($data['start_time']);
				$data['end_time'] = strtotime($data['end_time']);
				$data['part_ids'] = implode(',',$data['part_ids']);
				for($i = 0; $i < count($_FILES['upFile']['name']); $i++){
					
					$return = $this->uploadfile($i,$file_name);
					if(!$return){continue;}
					$files = array(
						'file_name'	=> $return['file_name'],
						'file_path'	=> $return['rtnResult'],
						'file_type'	=> $return['postfix'],
						'file_size'	=> $return['file_size']/1000,
					);
					
					//如果文件名没有对应的，就使用原名和默认数据
					
					
					$files['belong_to'] = 15;//归属协同管理
					$files['table_id'] = 293;
					//$datas = array_merge($data, $files);
					$results = $this->att_model->add($files);//存附件
					if($results){
						$data['attachment_ids'] .= $results.",";
					}
					
				}
				
				$result = $this->twork_model->add($data);
				if ($result!==false) {
					$this->success("添加成功！", U("TeamWorks/index"));
				} else {
					$this->error("添加失败！");
				}
			} else {
				$this->error($this->att_model->getError());
			}
		}
	}
	/*
	ajax获取版本
	*/
	public function get_types(){
		$type_id = $_GET['type_id'];
		$types = $this->type_model->where(array('type_id'=>$type_id))->order("id ASC")->select();
		echo json_encode($types);
	}
	/*
	星级标记
	*/
	public function is_target(){
		$id = $_GET['id'];
		if(!$id){
			$this->error("数据有误！");
		}
		$is_target = $_GET['is_target'];
		//$data['id'] = $id;
		$data['is_target'] = $is_target==0 ? 1 : 0;
		
		//if ($this->twork_model->create()!==false) {
			$result=$this->twork_model->where('id='.$id)->save($data);
			if ($result !== false) {
				$this->success("标记修改成功！", U("TeamWorks/index"));
			} else {
				$this->error("标记失败！");
			}
		//} else {
		//	$this->error($this->twork_model->getError());
		//}
	}
	/*
	详情页
	*/
	public function work_view(){
		$id = $_GET['id'];
		$admin_id = session('ADMIN_ID');
		if(!$id){
			$this->error("数据有误！");
		}
		$result = $this->twork_model->alias("t")
            ->field('t.*,ty.name tname,ty.type_id tyid,us.real_name resp_name,u.real_name propose_name,s.real_name approve_name,tu.study_num,c.comm_num')
            ->join(array(
            	 ' LEFT JOIN '.C('DB_PREFIX').'teamwork_type ty ON ty.id = t.type_id',//类型
				 ' LEFT JOIN '.C('DB_PREFIX').'users us ON us.id = t.resp_id',
				 ' LEFT JOIN '.C('DB_PREFIX').'users u ON u.id = t.propose_id',
				 ' LEFT JOIN '.C('DB_PREFIX').'users s ON s.id = t.approve_id',
				 ' LEFT JOIN (select id,twork_id,count(id) comm_num from hzzy_teamwork_comm group by twork_id) c ON c.twork_id = t.id',//沟通
				 ' LEFT JOIN (select id,twork_id,count(id) study_num from hzzy_teamwork_study group by twork_id) tu ON tu.twork_id = t.id',//心得
            	))
            ->where("t.id = ".$id)
            ->find();
		if(!$result){
			$this->error("任务查找失败！");
		}
		$work_atts = array();
		if($result['attachment_ids'] != ''){
			$att['id'] = array('in',$result['attachment_ids']);
			$work_atts = $this->att_model->where($att)->order("id ASC")->select();
		}
		$result['atts'] = $work_atts;//任务附件
		$pnames = '';
		if($result['part_ids'] != ''){
			$parts_name = $this->users_model->where("id in (".$result['part_ids'].")")->order("id ASC")->select();
			
			foreach($parts_name as $val){
				$pnames .= $val['real_name']."，";
			}
			$pnames = trim($pnames,'，');
		}
		$result['pnames'] = $pnames;//参与人
		$this->assign("result", $result);//传递总数据
		$comm = $this->comm_model->alias("c")
			->field('c.*,u.real_name,us.real_name reply_name')
			->join(array(
            	 ' LEFT JOIN '.C('DB_PREFIX').'users u ON u.id = c.user_id',
				 ' LEFT JOIN '.C('DB_PREFIX').'users us ON us.id = c.user_id',
            	))
			->where("twork_id = ".$id)
			->order('reply_time asc')
			->select();//沟通
		/* 记录为已查看沟通记录 start*/
		$comm_ids = $this->userlog_model->where('user_id = '.$admin_id )->find();
		$d['user_id'] = $admin_id;
		$d['update_time'] = time();
		if(empty($comm_ids)){
			$this->userlog_model->add($d);
		}
		$ids = $comm_ids['comm_ids'] ? $comm_ids['comm_ids'] : '0';
		$arr = explode(',',$ids);
		/* 记录为已查看沟通记录 end*/
		foreach($comm as $k=>$v){
			if($v['attachment_ids'] != ''){
				$att['id'] = array('in',$v['attachment_ids']);
				$atts = $this->att_model->where($att)->order("id ASC")->select();
				$comm[$k]['atts'] = $atts;//沟通附件
			}
			/* 记录为已查看沟通记录 start*/
			if(!in_array($v['id'],$arr)){
				$ids .= ','.$v['id'];
			}
			/* 记录为已查看沟通记录 end*/
		}
		$d['comm_ids'] = $ids;
		$this->userlog_model->where('user_id = '.$admin_id )->save($d);//保存查看记录
		$study = $this->study_model->alias("s")
			->field('s.*,u.real_name')
			->join(array(
            	 ' LEFT JOIN '.C('DB_PREFIX').'users u ON u.id = s.user_id',//类型
            	))
			->where("twork_id = ".$id)
			->order('add_time desc')->select();//心得
		$this->assign("comm", $comm);
		$this->assign("study", $study);
		$users = $this->users_model->order("id ASC")->select();
        $this->assign("users",$users);
		$this->display();
	}
	/*
	添加心得
	*/
	public function add_study(){
		if (IS_POST) {
			if($_POST['twork_id'] == ''){
				$this->error("数据对象有误！");
			}
			if($_POST['content'] == ''){
				$this->error("请填写心得！");
			}
			$data = $_POST;
			$data['user_id'] = session('ADMIN_ID');
			$data['add_time'] = time();
			if ($this->study_model->create()!==false ) {
					
				$result = $this->study_model->add($data);
				if ($result!==false) {
					$this->success("心得发布成功！", U("TeamWorks/work_view",array('id'=>$data['twork_id'])));
				} else {
					$this->error("心得发布失败！");
				}
			} else {
				$this->error($this->study_model->getError());
			}
		}
	}
	/*
	添加沟通记录
	*/
	public function add_comm(){
		if (IS_POST) {
			$return['sta'] = 0;
			$return['dates'] = array();
			if($_POST['twork_id'] == ''){
				$this->error("数据对象有误！");
			}
			if($_POST['content_comm'] == ''){
				$this->error("回复内容不能为空！");
			}
			$data = $_POST;
			$data['user_id'] = session('ADMIN_ID');
			$data['reply_time'] = time();
			$data['content'] = $_POST['content_comm'];
			if ($this->att_model->create()!==false && $this->comm_model->create()!==false ) {
				for($i = 0; $i < count($_FILES['upFile']['name']); $i++){
					
					$return = $this->uploadfile($i,$file_name);
					if(!$return){continue;}
					$files = array(
						'file_name'	=> $return['file_name'],
						'file_path'	=> $return['rtnResult'],
						'file_type'	=> $return['postfix'],
						'file_size'	=> $return['file_size']/1000,
					);
					
					//如果文件名没有对应的，就使用原名和默认数据
					
					
					$files['belong_to'] = 15;//归属协同管理
					$files['table_id'] = 293;
					//$datas = array_merge($data, $files);
					$results = $this->att_model->add($files);//存附件
					if($results){
						$data['attachment_ids'] .= $results.",";
					}
					
				}	
				$result = $this->comm_model->add($data);
				if ($result!==false) {
					$this->success("回复成功！", U("TeamWorks/work_view",array('id'=>$data['twork_id'],'bottom'=>'true')));
					
					
				} else {
					$this->error("回复失败！");
				}
			} else {
				$this->error($this->comm_model->getError());
			}
		}
		
	}
	/*
	沟通记录  zanting 
	*/
	public function get_comms(){
		if (IS_POST) {
			$return['sta'] = 0;
			$return['dates'] = array();
			if($_POST['twork_id'] == ''){
				//$this->error("数据对象有误！");
				$return['sta'] = 1;
			}
			if($_POST['content_comm'] == ''){
				//$this->error("回复内容不能为空！");
				$return['sta'] = 2;
			}
			$data = $_POST;
			$data['user_id'] = session('ADMIN_ID');
			$data['reply_time'] = time();
			$data['content'] = $_POST['content_comm'];
			if ($this->att_model->create()!==false && $this->comm_model->create()!==false ) {
				for($i = 0; $i < count($_FILES['upFile']['name']); $i++){
					
					$return = $this->uploadfile($i,$file_name);
					if(!$return){continue;}
					$files = array(
						'file_name'	=> $return['file_name'],
						'file_path'	=> $return['rtnResult'],
						'file_type'	=> $return['postfix'],
						'file_size'	=> $return['file_size']/1000,
					);
					
					//如果文件名没有对应的，就使用原名和默认数据
					
					
					$files['belong_to'] = 15;//归属协同管理
					$files['table_id'] = 293;
					//$datas = array_merge($data, $files);
					$results = $this->att_model->add($files);//存附件
					if($results){
						$data['attachment_ids'] .= $results.",";
					}
					
				}	
				$result = $this->comm_model->add($data);
				if ($result!==false) {
					//$this->success("回复成功！", U("TeamWorks/work_view",array('id'=>$data['twork_id'])));
					$id = $_POST['tid'];
					$admin_id = session('ADMIN_ID');
					$comm = $this->comm_model->alias("c")
						->field('c.*,u.real_name,us.real_name reply_name')
						->join(array(
							 ' LEFT JOIN '.C('DB_PREFIX').'users u ON u.id = c.user_id',
							 ' LEFT JOIN '.C('DB_PREFIX').'users us ON us.id = c.user_id',
							))
						->where("twork_id = ".$id)
						->order('reply_time asc')
						->select();//沟通
					/* 记录为已查看沟通记录 start*/
					$comm_ids = $this->userlog_model->where('user_id = '.$admin_id )->find();
					$d['user_id'] = $admin_id;
					$d['update_time'] = time();
					if(empty($comm_ids)){
						$this->userlog_model->add($d);
					}
					$ids = $comm_ids['comm_ids'] ? $comm_ids['comm_ids'] : '0';
					$arr = explode(',',$ids);
					/* 记录为已查看沟通记录 end*/
					foreach($comm as $k=>$v){
						if($v['attachment_ids'] != ''){
							$att['id'] = array('in',$v['attachment_ids']);
							$atts = $this->att_model->where($att)->order("id ASC")->select();
							$comm[$k]['atts'] = $atts;//沟通附件
						}
						/* 记录为已查看沟通记录 start*/
						if(!in_array($v['id'],$arr)){
							$ids .= ','.$v['id'];
						}
						/* 记录为已查看沟通记录 end*/
					}
					$d['comm_ids'] = $ids;
					$this->userlog_model->where('user_id = '.$admin_id )->save($d);//保存查看记录
					$return['dates'] = $comm;
					
				} else {
					//$this->error("回复失败！");
					$return['sta'] = 3;
				}
			} else {
				//$this->error($this->comm_model->getError());
				$return['sta'] = 4;
			}
			echo json_encode($return);
		}
		
	}
	/* ajax获取新信息*/
	public function get_mess(){
		$admin_id = session('ADMIN_ID');
		$now = time() - 10;
		
		//查询个人沟通记录查看表中看过的消息 ids
		$comm_ids = $this->userlog_model->where('user_id = '.$admin_id)->find();
		if(empty($comm_ids)){
			$d['user_id'] = $admin_id;
			$d['update_time'] = time();
			$this->userlog_model->add($d);
		}
		$ids = $comm_ids['comm_ids'] ? $comm_ids['comm_ids'] : '0';
		//$data['is_check'] = 1;
		//$res = $this->comm_model->where('twork_id='.$id)->save($data);
		
		//根据 时间查询所有 跟我有关且 不在ids中 的沟通记录
		$where = " 1=1 ";
		$where .= " and ( t.resp_id = ".$admin_id." or t.propose_id = ".$admin_id." or find_in_set('".$admin_id."',t.part_ids) or t.approve_id = ".$admin_id.")";
		$where .= " and c.comm_num != 0";
		//$where .= " and c.reply_time > ".$now;
		$results = $this->twork_model->alias("t")
            ->field('t.title,t.id,c.comm_num num')
            ->join(array(
				 ' LEFT JOIN (select id,twork_id,count(id) comm_num from hzzy_teamwork_comm where id not in  ('.$ids.') and (reply_id = '.$admin_id.' or '.$admin_id.' in ("at_ids")) group by twork_id) c ON c.twork_id = t.id',//沟通
            	))
            ->where($where)
            ->order("t.pub_time desc")
            ->select();
		
		$c_num = 0;
		foreach($results as $k=>$v){
			$results[$k]['title'] = msubstr($v['title'],0,7,"utf-8",true);
			$comm = $this->comm_model->alias("c")
				->field('c.id')
				->where('c.id not in  ('.$ids.') and (reply_id = '.$admin_id.' or '.$admin_id.' in ("at_ids")) and c.twork_id = '.$v['id'])
				->select();
			$c_num += count($comm);
		}
		
		//判断记录，如果有记录 以json方式 返回记录信息 ,任务名称 id 和信息个数
		$data = array();
		$data['c_num'] = $c_num;
		$data['data'] = $results;
		echo json_encode($data);
		
	}
	/**
	 *  删除心得
	 */
	public function del_study(){
	    $id = I('get.id',0,'intval');
		$d = $this->study_model->where(array('id' => $id))->find();
		//检测用户 非本人不能删除
		$admin_id = session('ADMIN_ID');
		if($admin_id != $d['user_id']){
			$this->error("禁止删除他人记录！");
		}
		if ($this->study_model->delete($id) !== false) {
			
			$this->success("删除成功！");
		} else {
			$this->error("删除失败！");
		}
	}
	/**
	 *  删除tonghua
	 */
	public function del_comm(){
	    $id = I('get.id',0,'intval');
		$d = $this->comm_model->where(array('id' => $id))->find();
		//检测用户 非本人不能删除
		$admin_id = session('ADMIN_ID');
		if($admin_id != $d['user_id']){
			$this->error("禁止删除他人记录！");
		}
		if ($this->comm_model->delete($id) !== false) {
			
			$this->success("删除成功！");
		} else {
			$this->error("删除失败！");
		}
	}
	/**
	 *  删除tonghua
	 */
	public function del_twork(){
	    $id = I('get.id',0,'intval');
		$d = $this->twork_model->where(array('id' => $id))->find();
		//检测用户 非本人不能删除
		$admin_id = session('ADMIN_ID');
		$role_id = D("Common/Users")->where('id='.session('ADMIN_ID'))->getField('role_id');
		if($admin_id != $d['propose_id'] && $role_id != 0){//发起人可以删除
			$this->error("你无权删除该任务！");
		}
		if(!$id){
			$this->error("数据有误！");
		}
		$model1 = $this->twork_model;
		$model2 = $this->comm_model;
		$model3 = $this->study_model;
		$model1->startTrans();
		$where['twork_id'] = array('=',$id);
		$res2 = $model2->where($where)->delete();
		$res3 = $model3->where($where)->delete();
		$res1 = $model1->delete($id);
		/*if ($this->twork_model->delete($id) !== false) {
			$this->comm_model->where('twork_id = '$id)->delete();
			$this->study_model->where('twork_id = '$id)->delete();
			$this->success("删除成功！", U("TeamWorks/index"));
		} else {
			$this->error("删除失败！");
		}*/
		if($res1 && $res2 && $res3){
			$model1->commit();  
			$this->success("删除成功！", U("TeamWorks/index"));
		}else{
			$model1->rollback();  //  条件不满足，回滚
			$this->error("删除失败！");
		}
	}
	
	
	/*
	修改任务
	*/
	public function edit(){
		$id = I('get.id',0,'intval');
		if($id == false){
			$this->error("请先选择要编辑的任务！", U("Result/index"));
		}
		$result = $this->twork_model->alias("f")
			->field('f.*')
			->where(array("f.id"=>$id))->find();
		if(empty($result)){
			$this->error("任务查找失败！", U("TeamWorks/index"));
		}
		$admin_id = session('ADMIN_ID');
		if($admin_id != $result['propose_id']){//发起人可以修改
			$this->error("你无权处理该任务！");
		}
		if($result['type_id'] != ''){
			$type = $this->type_model->where('id = '.$result['type_id'])->find();
			$types = $this->type_model->where('type_id = '.$type['type_id'])->order("id ASC")->select();
		}else{
			$type = '';
			$types = array();
		}
		
		
        $this->assign("type",$type);
		
        $this->assign("types",$types);
		$users = $this->users_model->order("id ASC")->select();
        $this->assign("users",$users);
		$departs = $this->departs_model->select();
		foreach($departs as $key=>$val){
			$us = $this->users_model->where("department_id = ".$val['id'])->order("id ASC")->select();
			$departs[$key]['users'] = $us;
		}
		$this->assign("departs",$departs);
		$this->assign("result", $result);
		
		$this->display();
	}
	/*
	修改任务
	*/
	public function edit_post(){
		if (IS_POST) {
			$data = $_POST;
			if ($this->twork_model->create()!==false) {
				$data['start_time'] = strtotime($data['start_time']);
				$data['end_time'] = strtotime($data['end_time']);
				$data['part_ids'] = implode(',',$data['part_ids']);
				$result=$this->twork_model->where('id='.$_POST['id'])->save($data);
				if ($result !== false) {
					$this->success("修改成功！", U("TeamWorks/index"));
				} else {
					$this->error("修改失败！");
				}
			} else {
				$this->error($this->twork_model->getError());
			}
		}
	}
	/*
	修改任务状态
	*/
	public function edit_status(){
		$status = $_GET['status'];
		$id = I('get.id',0,'intval');
		$d = $this->twork_model->where(array('id' => $id))->find();
		
		$admin_id = session('ADMIN_ID');
		if($admin_id != $d['resp_id']){//负责人可以
			$this->error("你无权处理该任务！");
		}
		if($d['verify_status'] == 1){
			$this->error("该任务已经通过审核！");
		}
		$data['id']	= $id;
		
			$data['status'] = $status;
			$result=$this->twork_model->where('id='.$id)->save($data);
			if ($result !== false) {
				$this->success("修改成功！", U("TeamWorks/work_view",array('id'=>$id)));
			} else {
				$this->error("修改失败！");
			}
		
		
	}
	/*
	s 审核任务状态
	*/
	public function verify_status(){
		$id = I('get.id',0,'intval');
		$d = $this->twork_model->where(array('id' => $id))->find();
		
		$admin_id = session('ADMIN_ID');
		if($admin_id != $d['approve_id']){//审核人可以
			$this->error("你无权审核该任务！");
		}
		$data['id']	= $id;
		$data['verify_status']	= 1;
			$result=$this->twork_model->where('id='.$id)->save($data);
			if ($result !== false) {
				$this->success("审核成功！", U("TeamWorks/work_view",array('id'=>$id)));
			} else {
				$this->error("审核失败！");
			}
		
		
	}
	/*
	新增版本
	*/
	public function add_type(){
		$types = $this->type_model->where('type_id = 1')->order("id ASC")->select();
        $this->assign("types",$types);
		
		$this->display();
	}
	/*
	新增版本-数据处理
	*/
	public function add_type_post(){
		if (IS_POST) {
			$data = $_POST;
			$data['manager_id'] = session('ADMIN_ID');
			$data['add_time'] = time();
			//防重复查询
			$types = $this->type_model->where(array('name'=>$data['name']))->order("id ASC")->select();
			if(!empty($types)){
				$this->error("添加失败,类目名称重复！");
			}
			if ($this->type_model->create()!==false) {
				$result=$this->type_model->add($data);
				if ($result !== false) {
					$this->success("添加成功！", U("TeamWorks/add_type"));
				} else {
					$this->error("添加失败！");
				}
			} else {
				$this->error($this->type_model->getError());
			}
		}
	}
	/*
     * 上传文件
     */
     public function uploadfile($i,$file_name){
        if(is_uploaded_file($_FILES['upFile']['tmp_name'][$i])){
            // 验证图片宽高信息
            $uploadSize = getimagesize($_FILES['upFile']['tmp_name'][$i]);
            $upfile = $_FILES["upFile"]; 
            //获取数组里面的值 
            $name = $upfile["name"][$i];//上传文件的文件名 
            $type = $upfile["type"][$i];//上传文件的类型 
            $size = $upfile["size"][$i];//上传文件的大小 
            $tmp_name = $upfile["tmp_name"][$i];//上传文件的临时存放路径 
            //处理文件名,有传入文件名则用，未传入就用原名
			if($file_name != false){
				$n = $file_name;
			}else{
				$n = $name;
			}
			$pos = strrpos($n,'.');
			if($pos != false){
				$fname = iconv("UTF-8","gbk", substr($n,0,$pos));
			}else{
				$fname = iconv("UTF-8","GB2312",$n);
			}
            // 上传结果
            $rtnType = "F";
            $destination = "";
            $error = $upFile["error"][$i];//上传后系统返回的值 
            if($error == 0){
                
                // 获取文件后缀
                $pathinfo = pathinfo($name);
                
                $destination = "data/upload/"."upFile"."/".date('Ymd'); 
                if (! file_exists ( $destination )) {
                    mkdir ( "$destination", 0777, true );
                }
                $destination .= "/".$fname."_".time().rand(100,999).'.'.$pathinfo['extension'];
                // 如果有原始图片地址信息，删除图片
                if(file_exists($_POST['imageURL'])){
                    unlink($_POST['imageURL']);
                }
                // 如果有原始图片地址信息，删除图片
				if(file_exists($_POST['imageURL'])){
					unlink($_POST['imageURL']);
				}
				//var_dump($destination);exit;
                //把上传的临时文件移动到up目录下面 
                move_uploaded_file($tmp_name, $destination); 
                $rtnType = "T";
                $rtnMsg = "文件上传成功啦！";
            }elseif ($error == 1){ 
                $rtnMsg = "超过了文件大小，在php.ini文件中设置"; 
            }elseif ($error == 2){ 
                $rtnMsg = "超过了文件的大小MAX_FILE_SIZE选项指定的值"; 
            }elseif ($error == 3){ 
                $rtnMsg = "文件只有部分被上传"; 
            }elseif ($error == 4){ 
                $rtnMsg = "没有文件被上传"; 
            }else{ 
                $rtnMsg = "上传文件大小为0"; 
            } 
            
            // 输出结果
            $return = array(
                'rtnType'	=> $rtnType,
                'rtnMsg'	=> $rtnMsg,
                'rtnResult'	=> iconv("GB2312","UTF-8",$destination),
                'file_name'	=> $name,
                'file_size'	=> $size,
                'postfix'	=> $pathinfo['extension'],
                'file_type' => $type
            );
			return $return;
            //return $file_name = $name;
        } else {
            // 输出结果
            //exit(json_encode(array(
            //    'rtnType'	=> "F",
            //    'rtnMsg'	=> "请选择上传文件"
            //)));
			//$this->error("请选择上传文件");
        }
    }
	/*
     * 上传文件
     */
     public function uploadexcel(){
        if(is_uploaded_file($_FILES['upExcel']['tmp_name'])){
            // 验证图片宽高信息
            $uploadSize = getimagesize($_FILES['upExcel']['tmp_name']);
            $upfile = $_FILES["upExcel"]; 
            //获取数组里面的值 
            $name = $upfile["name"];//上传文件的文件名 
            $type = $upfile["type"];//上传文件的类型 
            $size = $upfile["size"];//上传文件的大小 
            $tmp_name = $upfile["tmp_name"];//上传文件的临时存放路径 
            
            // 上传结果
            $rtnType = "F";
            $destination = "";
            $error = $upFile["error"];//上传后系统返回的值 
            if($error == 0){
                
                // 获取文件后缀
                $pathinfo = pathinfo($name);
                
                $destination = "data/upload/"."upExcel/".date('Ymd'); 
                if (! file_exists ( $destination )) {
                    mkdir ( "$destination", 0777, true );
                }
                $destination .= "/".time().'.'.$pathinfo['extension'];
                // 如果有原始图片地址信息，删除图片
                if(file_exists($_POST['imageURL'])){
                    unlink($_POST['imageURL']);
                }
                // 如果有原始图片地址信息，删除图片
				if(file_exists($_POST['imageURL'])){
					unlink($_POST['imageURL']);
				}
				
                //把上传的临时文件移动到up目录下面 
                move_uploaded_file($tmp_name, $destination); 
                $rtnType = "T";
                $rtnMsg = "文件上传成功啦！";
            }elseif ($error == 1){ 
                $rtnMsg = "超过了文件大小，在php.ini文件中设置"; 
            }elseif ($error == 2){ 
                $rtnMsg = "超过了文件的大小MAX_FILE_SIZE选项指定的值"; 
            }elseif ($error == 3){ 
                $rtnMsg = "文件只有部分被上传"; 
            }elseif ($error == 4){ 
                $rtnMsg = "没有文件被上传"; 
            }else{ 
                $rtnMsg = "上传文件大小为0"; 
            } 
            
            // 输出结果
            $res = array(
                'rtnType'	=> $rtnType,
                'rtnMsg'	=> $rtnMsg,
                'rtnResult'	=> $destination,
                'file_name'	=> $name,
                'file_size'	=> $size,
                'postfix'	=> $pathinfo['extension'],
                'file_type' => $type
            );
            //return $file_name = $name;
			return $res;
        } else {
            // 输出结果
            //exit(json_encode(array(
            //    'rtnType'	=> "F",
            //    'rtnMsg'	=> "请选择上传文件"
            //)));
			$this->error("请选择上传文件");
        }
    }
	/*
	 * 导入数据
	 * 工程项目报价汇总表  
	 **/
	public function import($filePath){
		require_once SPAPP_PATH.'Core/Library/Vendor/PHPExcel/PHPExcel.php';
		require_once SPAPP_PATH.'Core/Library/Vendor/PHPExcel/PHPExcel/Writer/Excel5.php';// 用于其他低版本xls 
		require_once SPAPP_PATH.'Core/Library/Vendor/PHPExcel/PHPExcel/Writer/Excel2007.php';// 用于 excel-2007 格式
		  
		//$filePath = $_POST['upExcel']['filePath'];
		$PHPExcel = new \PHPExcel();//实例化，一定要注意命名空间的问题加\ 

		/**默认用excel2007读取excel，若格式不对，则用之前的版本进行读取*/ 
		$PHPReader = new \PHPExcel_Reader_Excel2007(); 
		if(!$PHPReader->canRead($filePath)){ 
			$PHPReader = new \PHPExcel_Reader_Excel5(); 
			if(!$PHPReader->canRead($filePath)){ 
				$this->error('文件读取失败');
				return; 
			} 
		}
		//不需要读取整个Excel文件而获取所有工作表数组的函数
		$sheetNames  = $PHPReader->listWorksheetNames($filePath);
		$PHPExcel = $PHPReader->load($filePath);
		// 保存数组
		$savedata = array();
		for($i = 0; $i < count($sheetNames); $i++){
			//读取excel文件中的第一个工作表 
			$currentSheet = $PHPExcel->getSheet($i);
			//取得一共有多少行
			$allRow = $currentSheet->getHighestRow();
			$allColumn = $currentSheet->getHighestColumn();
			/**从第二行开始输出，因为excel表中第一行为列名*/ 
			for($currentRow = 2; $currentRow <= $allRow; $currentRow++){
				$file_name = trim($currentSheet->getCell("D".$currentRow)->getValue());
				if($file_name != ''){
					$savedata[$file_name]['ordernum']	= $currentSheet->getCell("A".$currentRow)->getValue();;
					$savedata[$file_name]['type_id']	= $currentSheet->getCell("B".$currentRow)->getValue();
					$savedata[$file_name]['figure_num']	= $currentSheet->getCell("C".$currentRow)->getValue();
					$savedata[$file_name]['file_name']	= $file_name;
					$savedata[$file_name]['sheet']	= $currentSheet->getCell("E".$currentRow)->getValue();
					$savedata[$file_name]['sheets']	= $currentSheet->getCell("F".$currentRow)->getValue();
				}
				
			}
		}
		return $savedata;
		// 导入完成 删除文件
		//unlink($filePath);
	}
	
}


?>